package cc.kzc.adminauth.auth.service.impl;

import java.util.List;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import cc.kzc.adminauth.auth.bo.LoginUser;
import cc.kzc.adminauth.common.ErrorCode;
import cc.kzc.adminauth.ds1.entity.AccountEO;
import cc.kzc.adminauth.ds1.repository.AccountRepository;
import cc.kzc.adminauth.exception.BaseError;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

	@Autowired
	private AccountRepository userRepository;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// 根据用户名查询用户信息
		List<AccountEO> userList = userRepository.findByAccount(username);
		AccountEO user = null;
		if (!CollectionUtils.isEmpty(userList)) {
			user = userList.get(0);
		}
		// 如果查询不到数据就通过抛出异常来给出提示
		if (Objects.isNull(user)) {
			throw new BaseError(ErrorCode.CLI_UNAUTHORIZED, "用户名或密码错误");
		}
		log.info("获取到的用户：{}", user);
		
		// TODO 根据用户查询权限信息 添加到LoginUser中

		// 封装成UserDetails对象返回
		return new LoginUser(user);
	}

}
